package com.fengwuj.mutils.aop.function;

import com.fengwuj.mutils.aop.annotation.Log;
import com.fengwuj.mutils.data.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 修订记录： jiangbo 2019/8/7 11:24 创建
 * @author jiangbo
 */
@Slf4j
@Aspect
@Configuration
@Order(1)
public class LogAspect {

	@Resource
	private SqlSession sqlSession;

	//定义切点方法
	@Pointcut("@annotation(com.fengwuj.mutils.aop.annotation.Log)")
	public void pointCut() {
		log.debug("日志切面标记方法");
	}

	@Around("pointCut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		//系统日志
		//获取到类，注入Logger注解
		Class<?> clazz = joinPoint.getTarget().getClass();
		//获取注解参数值，即业务信息
		MethodSignature methodSignature =(MethodSignature)joinPoint.getSignature();
		Method method = methodSignature.getMethod();
		Log logAnno = method.getAnnotation(Log.class);
		String message = logAnno.businessMessage();
		//获取到所有的参数值数组
		Object[] args = joinPoint.getArgs();
		String position1 = clazz.getName() + "." + joinPoint.getSignature().getName() + "():入参:";
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < args.length; i++) {
			stringBuilder.append(JsonUtils.writeValueAsString(args[i]));
		}
		String inResult = stringBuilder.toString();
		log.info(message);
		log.info("{}\t{}", position1, inResult);
		//开始执行Controller
		Object object = joinPoint.proceed();
		//Controller执行完成
		//切面切入
        //通过泛型查询
        //entityClass = (Class) ((ParameterizedType)mapper.getClass().getInterfaces()[0].getGenericInterfaces()[0])
                //.getActualTypeArguments()[0];
		//系统日志
		String position2 = clazz.getName() + "." + joinPoint.getSignature().getName() + "():出参:";
		log.info("{}\t{}", position2, JsonUtils.writeValueAsString(object));
		return object;
	}
}
